package org.jivesoftware.openfire.plugin.chatlogs;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.server.Authentication;
import org.jivesoftware.admin.AuthCheckFilter;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.openfire.plugin.common.ResponseMessage;
import org.jivesoftware.openfire.plugin.common.Result;
import org.jivesoftware.openfire.plugin.model.ChatLogs;
import org.jivesoftware.openfire.plugin.model.Group;
import org.jivesoftware.openfire.plugin.model.GroupChatLogs;
import org.jivesoftware.openfire.plugin.model.User;
import org.jivesoftware.util.ParamUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 聊天记录插件对外接口
 *
 * @author lyusantu@gmail.com
 */
public class ChatLogsServlet extends HttpServlet {

    //退群
    private static final String QUIT_ROOM = "DELETE FROM ofMucMember WHERE roomId = ? and nickname = ?";

    private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    private static DbChatLogsManager logsManager;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        logsManager = DbChatLogsManager.getInstance();
        // 取消权限验证，不登陆即可访问 111
        AuthCheckFilter.addExclude("chatlogs");
        AuthCheckFilter.addExclude("chatlogs/ChatLogsServlet");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ChatLogs entity = new ChatLogs();
        String action = ParamUtils.getParameter(request, "action");
        //TODO 删除单条聊天记录
        if ("remove!contact".equals(action)) {
            Integer messageId = ParamUtils.getIntParameter(request, "messageId", -1);
            logsManager.remove(messageId);
            request.getRequestDispatcher("/plugins/chatlogs/chatLogs-service.jsp").forward(request, response);
            // 第一次查询时返回所有聊天记录的十条
        }
        //TODO Serlet API
        // 会话列表
        else if ("user!contact!json".equals(action)) {
            userContacts(request, response, out, entity);
        }
        // 单聊聊天记录
        else if ("query!logs".equals(action)) {
            chatRecords(request, response, out, entity);
        }
        // 群聊聊天记录
        else if ("queryGroup!logs".equals(action)) {
            groupChatRecords(request, response, out, entity);
        }
        // 新的会话列表,返回单聊 + 群聊并排序
        else if ("sessionList".equals(action)) {
            sessionList(request, response, out, entity);
        }
        // 删除某条聊天记录
        else if ("delete!contact!json".equals(action)) {
            Integer messageId = ParamUtils.getIntParameter(request, "messageId", -1);
            replyMessage(JSON.toJSONString(logsManager.remove(messageId)), response, out);

        }else {
            replyMessage(JSON.toJSONString("FBI WARNING"), response, out);
        }
    }


    /**
     * 会话列表
     */
    private void userContacts(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ChatLogs entity) {
        try {
            String sender = ParamUtils.getParameter(request, "sender");
            entity.setSender(sender);
            List<User> result = logsManager.singleChatSessionList(entity);
            String data = HttpUtils.send(HttpUtils.BASE_URL,result == null ? null : JSON.toJSONString(result));
                if (StringUtils.isNotEmpty(data)) {
                    JSONObject jsonObject = JSON.parseObject(data);
                    if (jsonObject.getInteger("code").intValue() == 0) {
                        jsonObject = this.getSingleChatSessionList(jsonObject, entity);
                        replyMessage(JSON.toJSONString(jsonObject), response, out);
                    } else {
                        replyMessage(data, response, out);
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
    }

    /**
     * 单聊聊天记录
     */
    private void chatRecords(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ChatLogs entity) {
        String sender = ParamUtils.getParameter(request, "sender");
        String receiver = ParamUtils.getParameter(request, "receiver");
        String uuid = ParamUtils.getParameter(request, "uuid");
        int pageSize = ParamUtils.getIntParameter(request, "pageSize", 10);
        entity.setSender(sender);
        entity.setReceiver(receiver);
        entity.setUuid(uuid);
        Result result = logsManager.queryLogs(entity, pageSize);
        replyMessage(JSON.toJSONString(result), response, out);
    }

    /**
     * 群聊聊天记录
     */
    private void groupChatRecords(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ChatLogs entity) {
        String receiver = ParamUtils.getParameter(request, "receiver");
        String uuid = ParamUtils.getParameter(request, "uuid");
        String flag = ParamUtils.getParameter(request, "flag");
        int pageSize = ParamUtils.getIntParameter(request, "pageSize", 10);
        entity.setReceiver(receiver);
        entity.setUuid(uuid);
        entity.setFlag(flag);
        Result result = logsManager.queryGroupLogs(entity, pageSize);
        replyMessage(JSON.toJSONString(result), response, out);
    }

    /**
     * 新的会话列表(返回排序后的单聊 + 群聊)
     */
    private void sessionList(HttpServletRequest request, HttpServletResponse response, PrintWriter out, ChatLogs entity) {
        // 单聊
        String sender = ParamUtils.getParameter(request, "sender");
        entity.setSender(sender);
        List<User> result = logsManager.singleChatSessionList(entity);
        String data = HttpUtils.send(HttpUtils.BASE_URL,result == null ? null : JSON.toJSONString(result));
        JSONObject jsonObject = JSON.parseObject(data);
        int code = jsonObject.getInteger("code").intValue();
        if (code == 0) {
            jsonObject = this.getSingleChatSessionList(jsonObject, entity);
        }
        // 群聊
        JSONArray array = null;
        List<User> groupChatList = logsManager.groupChatSessionList(entity);
        if (groupChatList != null && groupChatList.size() > 0) {
            array = getGroupChatSessionList(groupChatList);
        }
        // 既没有单聊也没有群聊时
        if (code != 0 && array == null) {
            replyMessage(JSON.toJSONString(jsonObject), response, out);
        }
        // 有单聊无群聊
        else if (code == 0 && array == null) {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonArray.getJSONObject(i).put("type", "chat");
            }
            replyMessage(JSON.toJSONString(jsonObject), response, out);
        }
        // 有群聊无单聊
        else if (code != 0 && array != null) {
            jsonObject.put("code", 0);
            jsonObject.put("message", "操作成功！");
            jsonObject.put("data", array);
            replyMessage(JSON.toJSONString(jsonObject), response, out);
        }
        // 群聊 & 单聊
        else {
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            for (int i = 0; i < array.size(); i++) {
                JSONObject groupObj = array.getJSONObject(i);
                Timestamp time = groupObj.getTimestamp("createDate");
                boolean flag = false;
                for (int j = 0; j < jsonArray.size(); j++) {
                    JSONObject obj = jsonArray.getJSONObject(j);
                    if (obj.getString("type") == null) {
                        obj.put("type", "chat");
                    }
                    Timestamp chatTime = obj.getTimestamp("createDate");
                    if (time.after(chatTime)) {
                        jsonArray.add(j, groupObj);
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    jsonArray.add(groupObj);
                }
            }
            replyMessage(JSON.toJSONString(jsonObject), response, out);
        }
    }

    /**
     * 单聊会话列表
     */
    private JSONObject getSingleChatSessionList(JSONObject jsonObject, ChatLogs entity) {
        JSONArray array = jsonObject.getJSONArray("data");
        for (int i = 0; i < array.size(); i++) {
            entity.setSender(entity.getSender());
            entity.setReceiver(array.getJSONObject(i).getString("userId"));
            array.getJSONObject(i).put("content", array.getJSONObject(i).getString("content"));
            array.getJSONObject(i).put("list", logsManager.queryLogs(entity, 10).getData());
        }
        return jsonObject;
    }

    /**
     * 群聊会话列表
     */
    private JSONArray getGroupChatSessionList(List<User> list) {
        JSONArray array = new JSONArray();
        for (User user : list) {
            Group group = logsManager.queryGroupInfo(user.getReceiver());
            if (group == null) {
                continue;
            }
            JSONObject object = new JSONObject();
            object.put("roomId", group.getRoomId());
            object.put("name", group.getName());
            object.put("naturalName", group.getNaturalName());
            object.put("description", group.getDescription());
            object.put("type", "groupChat");
            ChatLogs entity = new ChatLogs();
            entity.setReceiver(user.getReceiver());
            List<GroupChatLogs> chatLogs = logsManager.getGroupChatRecords(entity, 10);
            if (chatLogs != null && chatLogs.size() > 0) {
                GroupChatLogs logs = chatLogs.get(0);
                object.put("sender", logs.getSender());
                object.put("nickName", logs.getNickName());
                object.put("content", logs.getContent());
                object.put("createDate", logs.getCreateDate());

            }
            object.put("list", (chatLogs != null && chatLogs.size() > 0) ? ResponseMessage.SUCCESS.messageToResult(chatLogs).getData() : ResponseMessage.SUCCESS_NOT_FOUND.messageToResult().getData());
            array.add(object);
        }
        return array;
    }

    @Override
    public void destroy() {
        super.destroy();
        // Release the excluded URL
        AuthCheckFilter.removeExclude("chatlogs/ChatLogsServlet");
        AuthCheckFilter.removeExclude("chatlogs");
    }

    private void replyMessage(String message, HttpServletResponse response, PrintWriter out) {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        out.write(message);
        out.close();
    }

}
